﻿using System;
using System.Linq;
using System.Xml;
using Colligate;

namespace OrgDataSource
{
// ReSharper disable InconsistentNaming
    public class TaskDS:IOrgDS
// ReSharper restore InconsistentNaming
    {
        #region\\delete
        public int DeleteTaskData(OUDataInfo UserInfo, string DataGuid, string DataType, orgEntities context)
        {
            switch (DataType.ToLower())
            {
                case "task": return DeleteWorkTask(DataGuid, context);
                default: throw new Exception("TaskDS无法处理该" + DataType + "的数据");
            }
        }

        private static int DeleteWorkTask(string DataGuid, orgEntities context)
        {
            try
            {
                var worktask = context.WorkTask.FirstOrDefault(cc => cc.Guid == DataGuid);
                context.DeleteObject(worktask);
                var result = context.SaveChanges();
                return result == 1 ? 0 : 1;
            }
            catch
            {
                throw new Exception("删除数据标识为：" + DataGuid + "的TaskDS数据时出错！");
            }
        }
        #endregion
        #region\\get
        public XmlNode GetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context, BaseTaskDataSource baseInfo)
        {
            switch (dataType.ToLower())
            {
                case "task": return GetWorkTask(dataGuid, context);
                default: throw new Exception("TaskDS无法处理该" + dataType + "的数据");
            }
        }

        private static XmlNode GetWorkTask(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "Task");
                var worktask = context.WorkTask.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new WorkTask
                                                                                                 {
                                                                                                     Guid = string.Empty,
                                                                                                     Name = string.Empty,
                                                                                                     AppGuid = string.Empty,
                                                                                                     OUDataInfoGuid = string.Empty,
                                                                                                     Status = string.Empty,
                                                                                                     TaskType = string.Empty,
                                                                                                     Sort = null
                                                                                                 };
                XmlNodeManage.SetSubValue(result, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), worktask.Guid);
                XmlNodeManage.SetSubValue(result, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), worktask.Name);
                XmlNodeManage.SetSubValue(result, "AppGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), worktask.AppGuid);
                //XmlNodeManage.SetSubValue(result, "ListOUDataInfo", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), worktask.OUDataInfoGuid);
                XmlNodeManage.SetSubValue(result, "Status", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), worktask.Status);
                XmlNodeManage.SetSubValue(result, "TaskType", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), worktask.TaskType);
                XmlNodeManage.SetSubValue(result, "Order", Enum.GetName(typeof(TypeEnum), TypeEnum.LONG), worktask.Sort);
                var memberNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                foreach (var member in worktask.TaskMember)
                {
                    var ouNode = XmlNodeManage.CreateNode("OUDataInfo");
                    var strName = string.Empty;
                    var temp = member;
                    switch(member.Type.ToLower().Trim())
                    {
                        case "application": strName = context.Application.FirstOrDefault(cc => cc.Guid == temp.MemberId).Name;
                            break;
                        case "company": strName = context.Company.FirstOrDefault(cc => cc.Guid == temp.MemberId).Name;
                            break;
                        case "branch": strName = context.Branch.FirstOrDefault(cc => cc.Guid == temp.MemberId).Name;
                            break;
                        case "member": strName = context.Member.FirstOrDefault(cc => cc.Guid == temp.MemberId).Name;
                            break;
                        case "group": strName = context.Group.FirstOrDefault(cc => cc.Guid == temp.MemberId).Name;
                            break;
                    }
                    XmlNodeManage.SetSubValue(ouNode, "@GUID", member.MemberId);
                    XmlNodeManage.SetSubValue(ouNode, "@Name", strName);
                    XmlNodeManage.SetSubValue(ouNode, "@OUType", member.Type);
                    XmlNodeManage.SetSubValue(ouNode, "@CompanyGuid", member.CompanyGuid);
                    memberNode.AppendChild(ouNode);
                }
                result.AppendChild(memberNode);
                return result;
            }
            catch
            {
                throw new Exception("获取数据标识为：" + dataGuid + "的Task数据时出错！");
            }
        }
        #endregion
        #region\\set
        public int SetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, XmlNode xmlData, orgEntities context)
        {
            var datatype = XmlNodeManage.GetSubValue(xmlData, "@DataType");
            switch (datatype.ToLower())
            {
                case "task":return SetWorkTask(xmlData, context);
                default: throw new Exception("TaskDS无法处理该" + datatype + "的数据");
            }
        }

        private static int SetWorkTask(XmlNode xmlData, orgEntities context)
        {
            System.Data.Common.DbTransaction tran = null;
            try
            {
                context.Connection.Open();
                tran = context.Connection.BeginTransaction();
                var id = Utility.CheckXmlData(xmlData,"Guid");
                var worktask = context.WorkTask.FirstOrDefault(cc => cc.Guid == id);
                if (null == worktask)
                {
                    worktask = new WorkTask
                                   {
                                       Guid = id,
                                       Name = Utility.CheckXmlData(xmlData, "Name"),
                                       AppGuid = Utility.CheckXmlData(xmlData, "AppGuid"),
                                       Status = Utility.CheckXmlData(xmlData, "Status"),
                                       TaskType = Utility.CheckXmlData(xmlData, "TaskType"),
                                       Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order")),
                                       OUDataInfoGuid = string.Empty
                                   };
                    context.AddToWorkTask(worktask);
                }
                else
                {
                    worktask.Name = Utility.CheckXmlData(xmlData,"Name");
                    worktask.AppGuid = Utility.CheckXmlData(xmlData,"AppGuid");
                    worktask.Status = Utility.CheckXmlData(xmlData,"Status");
                    worktask.TaskType = Utility.CheckXmlData(xmlData,"TaskType");
                    worktask.Sort = int.Parse(Utility.CheckXmlData(xmlData,"Order"));
                }
                context.SaveChanges();
                if(worktask.TaskMember.Count!=0)
                {
                    var memberList = worktask.TaskMember.ToList();
                    foreach (var t in memberList)
                        context.TaskMember.DeleteObject(t);
                }
                const string queryStr = "ListOUDataInfo/OUDataInfo";
                var temp = xmlData.SelectNodes(queryStr) ?? xmlData.SelectNodes(queryStr.ToLower());
                //var tt = temp[0].Attributes["GUID"];
                foreach (var taskMember in from XmlNode item in temp
                                           select new TaskMember
                                                      {
                                                          Guid = Guid.NewGuid().ToString(), 
                                                          TaskId = worktask.Guid, 
                                                          MemberId = item.Attributes["GUID"].Value, 
                                                          Type = item.Attributes["OUType"].Value, 
                                                          CompanyGuid = item.Attributes["CompanyGuid"].Value
                                                      })
                {
                    worktask.TaskMember.Add(taskMember);
                }
                context.SaveChanges();
                tran.Commit();
                return 0;
            }
            catch
            {
                if (tran != null)
                    tran.Rollback();
                throw new Exception("写入Task数据时出错！");
            }
            finally
            {
                if (context != null && context.Connection.State != System.Data.ConnectionState.Closed)
                    context.Connection.Close();
            }
        }
        #endregion
        #region\\transform
        public XmlNode TransformTaskData(OUDataInfo userInfo, XmlNode xmlParam, orgEntities context, BaseTaskDataSource baseInfo)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
